package com.bst.bsj.bops.web.filter;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bst.bsj.bops.BopsConstants;
import com.bst.bsj.bops.NotFilterConstants;
import com.bst.bsj.portal.util.AuthUtil;
import com.bst.bsj.portal.util.JsonSerializable;
import com.homewaimai.common.lang.StringUtil;
import com.homewaimai.framework.web.Constants;
import com.homewaimai.framework.web.request.session.AuthSecureContextHolder;
import com.homewaimai.framework.web.request.session.LoginUser;
import com.homewaimai.framework.web.request.session.UserAuthenticationContext;

public class UserLoginFilter implements Filter {

  private FilterConfig config;

  public void destroy() {
    config = null;
  }

  public void needLogined(HttpServletResponse response) {
    response.setContentType("text/html;charset=utf-8");
    Writer wr = null;
    try {
      wr = response.getWriter();
      wr.write(new String((new JsonSerializable()).serialize("403", "you need login!"), "UTF-8"));
      wr.flush();
    } catch (Exception e) {
      try {
        wr.write(new String((new JsonSerializable()).serialize("500", "excute  error!"), "UTF-8"));
        wr.flush();
      } catch (Exception e1) {
      }
    } finally {
      try {
        wr.close();
      } catch (Exception e1) {
      }
    }
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
      ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String loginUserStr = (String) req.getSession().getAttribute(Constants.COOKIE_LOGIN_USER);

    if (null == loginUserStr) {

      req.getSession().setAttribute(Constants.COOKIE_LOGINED, "false");
      resp.sendRedirect("/bops/login.htm");
      return;

    }

    //获取请求的uri    
    String uri = req.getRequestURI();
    uri = uri.substring(0, uri.lastIndexOf("/"));
    boolean flag = false;

    String lastUrl = uri.substring(uri.lastIndexOf("/")); //不拦截路径判断
    if (NotFilterConstants.NOT_FILTER_LIST.contains(lastUrl)) {
      flag = true;
    } else {
      String menuStr = (String) req.getSession().getAttribute("urlList");
      if (menuStr.contains(uri)) {
        flag = true;
      }

    }

    //如果uri不在请求的权限菜单之内，则视为权限不足，需用正确帐户重新登录    
    if (!flag) {
      String redirect = req.getRequestURI(); //获取重新登录后的请求路径
      resp.sendRedirect("/bops/login.htm?redirectUrl=" + redirect);
      return;
    }

    //检查登录子系统
    String subsystem = (String) req.getSession().getAttribute(Constants.COOKIE_SUBSYSTEM);
    if (StringUtil.isBlank(subsystem) || !BopsConstants.SUB_SYSTEM.equals(subsystem)) {
      req.getSession().setAttribute(Constants.COOKIE_LOGINED, "false");
      resp.sendRedirect("/bops/login.htm");
      return;
    }

    // 检验loginUserStr 是否合法
    LoginUser loginUser = convertLoginUserFromCookie(loginUserStr);
    AuthUtil.setAuthToken(req, loginUser);
    UserAuthenticationContext userAuthenticationContext = new UserAuthenticationContext(loginUser);
    // 默认不到数据库校验
    userAuthenticationContext.setAuthenticated(true);
    AuthSecureContextHolder.setContext(userAuthenticationContext);
    if ("true".equals(req.getSession().getAttribute(Constants.COOKIE_LOGINED))) {
      req.getSession().setAttribute(Constants.COOKIE_LOGINED, "true");
    }
    String nickName = loginUser.getNickName();
    if (StringUtil.isBlank(nickName)) {
      nickName = loginUser.getMemberId();
    }
    // nickName = java.net.URLEncoder.encode(nickName,"utf-8");
    req.getSession().setAttribute(Constants.COOKIE_NICKNAME, nickName);
    req.getSession().setAttribute(Constants.COOKIE_LAST_LOGINID, loginUser.getMemberId());
    String subMenu = req.getParameter("subMenu");
    if (subMenu != null)
      req.getSession().setAttribute("subMenu", subMenu);
    chain.doFilter(request, response);
  }

  private LoginUser convertLoginUserFromCookie(String loginUserStr) {
    String[] cookies = loginUserStr.split("&");
    Map<String, String> map = new HashMap<String, String>(cookies.length);
    for (String cooke : cookies) {
      String[] keyValue = cooke.split("=");
      if (keyValue.length >= 2) {
        map.put(keyValue[0], keyValue[1]);
      }
    }
    LoginUser loginUser = new LoginUser();
    loginUser.setLogined(Boolean.parseBoolean(map.get(LoginUser.COOKIE_LOGINED)));
    loginUser.setLoginId(Long.parseLong(map.get(LoginUser.COOKIE_LOGIN_ID)));
    loginUser.setMemberId(map.get(LoginUser.COOKIE_M_ID));
    loginUser.setmLevel(map.get(LoginUser.COOKIE_M_LEVEL));
    loginUser.setTs(map.get(LoginUser.COOKIE_TS));
    loginUser.setNickName(map.get(LoginUser.COOKIE_NICK_NAME));
    return loginUser;
  }

  public void init(FilterConfig config) throws ServletException {
    this.config = config;
  }

}
